const app = getApp()
const config = app.globalData.config

Page({
  data: {
    activity: null,
    teams: [],
    answerTypes: ['选择题', '文字题', '视频题', '图片题'],
    tasks: [],
    isActivityCompleted: false
  },

  onLoad: function (options) {
    if (options.activity) {
      const activity = JSON.parse(decodeURIComponent(options.activity));
      
      // 只在状态为4时为已完成
      const isActivityCompleted = activity.activityStatus === '4';
      
      this.setData({ 
        activity,
        isActivityCompleted
      });
      
      this.loadTasks(activity.id);
    }
  },

  // 加载活动对应的任务列表
  loadTasks: function (activityId) {
    wx.showLoading({
      title: '加载中',
    });

    // 获取存储的cookies
    const cookies = wx.getStorageSync('cookies');
    if (!cookies) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/coach/login/login'
            })
          }, 1500)
        }
      })
      return
    }

    // 调用后端API获取任务列表
    wx.request({
      url: config.baseUrl[config.env] + config.apiPath.activity.task,
      method: 'POST',
      header: {
        'Cookie': cookies,
        'Content-Type': 'application/json'
      },
      data: {
        activityId: activityId,
        taskName: '',
        taskDesc: '',
        taskLevel: null,
        taskType: ''
      },
      success: res => {
        const { errorCode, data } = res.data
        if (errorCode === '000000') {
          // 转换为驼峰命名
          const tasks = (data || []).map(task => ({
            taskName: task.taskName || task.task_name,
            taskDesc: task.taskDesc || task.task_desc,
            taskLevel: task.taskLevel || task.task_level,
            taskType: task.taskType || task.task_type,
            imagePath: task.imagePath || task.image_path,
            activityId: task.activityId || task.activity_id
          }));
          this.setData({ tasks });
        } else {
          wx.showToast({
            title: '获取任务列表失败',
            icon: 'none'
          })
        }
      },
      fail: err => {
        console.error('获取任务列表失败：', err)
        wx.showToast({
          title: '获取任务列表失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 加载队伍列表
  loadTeams(activityId) {
    wx.cloud.callFunction({
      name: 'getTeams',
      data: { activityId }
    }).then(res => {
      this.setData({
        teams: res.result.data
      })
    }).catch(err => {
      console.error('获取队伍列表失败：', err)
      wx.showToast({
        title: '获取队伍列表失败',
        icon: 'none'
      })
    })
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      '0': '待支付',
      '1': '已支付',
      '2': '已测试',
      '3': '已开始',
      '4': '已完成'
    }
    return statusMap[status] || '未知状态'
  },

  // 生成队伍二维码
  generateQRCode() {
    wx.showLoading({
      title: '生成二维码中'
    })

    wx.cloud.callFunction({
      name: 'generateTeamQRCode',
      data: {
        activityId: this.data.activity._id,
        teamCount: this.data.activity.teamCount
      }
    }).then(res => {
      wx.hideLoading()
      // 跳转到二维码展示页面
      wx.navigateTo({
        url: `/pages/coach/teamQRCode/teamQRCode?activityId=${this.data.activity._id}`
      })
    }).catch(err => {
      console.error('生成二维码失败：', err)
      wx.hideLoading()
      wx.showToast({
        title: '生成二维码失败',
        icon: 'none'
      })
    })
  },

  // 开始活动
  startActivity() {
    wx.showModal({
      title: '确认开始',
      content: '开始活动后，队员将可以开始完成任务，是否确认开始？',
      success: res => {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: 'startActivity',
            data: {
              activityId: this.data.activity._id
            }
          }).then(() => {
            wx.showToast({
              title: '活动已开始',
              icon: 'success'
            })
            this.loadTasks(this.data.activity._id)
          }).catch(err => {
            console.error('开始活动失败：', err)
            wx.showToast({
              title: '开始活动失败',
              icon: 'none'
            })
          })
        }
      }
    })
  },

  // 结束活动
  endActivity() {
    wx.showModal({
      title: '确认结束',
      content: '结束活动后，队员将无法继续提交任务，是否确认结束？',
      success: res => {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: 'endActivity',
            data: {
              activityId: this.data.activity._id
            }
          }).then(() => {
            wx.showToast({
              title: '活动已结束',
              icon: 'success'
            })
            this.loadTasks(this.data.activity._id)
          }).catch(err => {
            console.error('结束活动失败：', err)
            wx.showToast({
              title: '结束活动失败',
              icon: 'none'
            })
          })
        }
      }
    })
  },

  // 新增任务
  addTask() {
    wx.navigateTo({
      url: '/pages/coach/taskEdit/taskEdit',
      events: {
        addTask: (task) => {
          const tasks = this.data.tasks || [];
          tasks.push(task);
          this.setData({ tasks });
        }
      }
    });
  },

  // 编辑任务
  editTask(e) {
    const { index } = e.currentTarget.dataset;
    const task = this.data.tasks[index];
    wx.navigateTo({
      url: `/pages/coach/taskEdit/taskEdit?task=${JSON.stringify(task)}&index=${index}`,
      events: {
        editTask: (data) => {
          const tasks = this.data.tasks;
          tasks[index] = data;
          this.setData({ tasks });
        }
      }
    });
  },

  // 删除任务
  deleteTask(e) {
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个任务吗？',
      success: (res) => {
        if (res.confirm) {
          const tasks = this.data.tasks;
          tasks.splice(index, 1);
          this.setData({ tasks });
        }
      }
    });
  },

  // 输入处理函数
  onNameInput(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.activityName': e.detail.value
    });
  },

  onDescInput(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.activityDesc': e.detail.value
    });
  },

  onDaysInput(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.activityDays': e.detail.value
    });
  },

  onTotalPeopleInput(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.totalPeople': e.detail.value
    });
  },

  onThemeInput(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.activityTheme': e.detail.value
    });
  },

  onTeamCountInput(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.teamCount': e.detail.value
    });
  },

  onTeamSizeInput(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.teamSize': e.detail.value
    });
  },

  onStartTimeChange(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.dailyStartTime': e.detail.value
    });
  },

  onEndTimeChange(e) {
    if (this.data.isActivityCompleted) return;
    this.setData({
      'activity.dailyEndTime': e.detail.value
    });
  },

  // 保存活动信息
  saveActivity() {
    const activity = this.data.activity;
    const tasks = this.data.tasks;

    // 表单验证
    if (!activity.activityName || !activity.activityDesc || !activity.activityDays || 
        !activity.totalPeople || !activity.activityTheme || !activity.teamCount || 
        !activity.teamSize || !activity.dailyStartTime || !activity.dailyEndTime) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '保存中'
    });

    // 获取存储的cookies
    const cookies = wx.getStorageSync('cookies');
    if (!cookies) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/coach/login/login'
            });
          }, 1500);
        }
      });
      return;
    }

    // 组装提交数据
    const submitData = {
      ...activity,
      tasks: (tasks || []).map(task => ({
        taskName: task.taskName,
        taskDesc: task.taskDesc,
        taskLevel: task.taskLevel,
        taskType: task.taskType,
        imagePath: task.imagePath,
        activityId: task.activityId
      }))
    };

    // 调用后端API更新活动信息
    wx.request({
      url: config.baseUrl[config.env] + '/coach/activity/update',
      method: 'POST',
      header: {
        'Cookie': cookies,
        'Content-Type': 'application/json'
      },
      data: submitData,
      success: res => {
        const { errorCode } = res.data;
        if (errorCode === '000000') {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        console.error('保存活动信息失败：', err);
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
}) 